import axios, { Method } from 'axios'
import errCode from '@/constants/errResponse'

/**
 * 请求开始，
 * @param {Object} config
 */
function startRequest(config:any) {
  /* 添加token */
  config.headers.Authorization = localStorage.getItem('token') ? `Bearer ${ localStorage.getItem('token') }` : ''
  return config
}

/**
 * 请求成功
 */
function responseSuccess(response:any) {
  return Promise.resolve(response)
}

/**
 * 响应数据检查
 */
function checkRes(response:any) {
  const data = response.data

  if (!data) {
    return Promise.reject('服务器返回数据空')
  }
  return data
}

/**
 * 发送请求错误
 */
function requestError(request:Request) {
  console.log('请求错误==========', request)
}

/**
 * 响应错误
 */
function responseError(err:Error) {
  /* 特殊处理 */
  if (err.message === '取消请求') {
    return Promise.reject(err)
  }
  console.log(`响应错误`, err)
  return Promise.reject(err)
}

/* 创建请求实例 */
const instance = axios.create({
  baseURL: process.env.REACT_APP_API,
  timeout: 10000, // 超时时间
  headers: {
    'content-type': 'application/json;chartset=UTF-8',
  },
})

/* 请求拦截 */
instance.interceptors.request.use(startRequest, requestError)
/* 响应拦截 */
instance.interceptors.response.use(responseSuccess, responseError)

function request(url:string, data:any = {}, config:any = {}, method:Method) {
  /* 去空 */
  for (const key in data) {
    if (data[ key ] === null || data[ key ] === undefined) {
      delete data[ key ]
    }
  }
  return instance.request({
    url,
    method,
    data: method === 'GET' ? null : data,
    params: method === 'GET' ? data : null, // get请求不携带data，params放在url上
    ...config, // 用户自定义配置，可以覆盖前面的配置
  })
    .then(checkRes)
}

/**
 * api请求方式
 * @param {String} url
 * @param {Any} params
 * @param {Object} config
 * @returns
 */
export function GET(url:string, params?:any, config?:any) {
  return request(
    url,
    params,
    config,
    'GET',
  )
}

export function POST(url:string, data?:any, config?:any) {
  return request(
    url,
    data,
    config,
    'POST',
  )
}

export function PUT(url:string, data?:any, config?:any) {
  return request(
    url,
    data,
    config,
    'PUT',
  )
}

export function DELETE(url:string, config?:any) {
  return request(
    url,
    {},
    config,
    'DELETE',
  )
}

